﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Cashier_Interface;
using Cashier_Service;
using Cashier.utils;
using Cashier_Utils;

namespace Cashier.purchase
{
    public partial class RepurchaseListControl : UserControl, IDataGridViewData, IReloadData, IPrinter
    {
        private MainForm mainform;
        private static RepurchaseListControl repurchaseListControl;
        private BillRepurchaseService repurchaseService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        private RepurchaseListControl(MainForm mainform)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.dataGridView1.ImplementsInstance = this;
            this.repurchaseService = new BillRepurchaseService();

            this.ControlsSetRights();
            this.Dock = DockStyle.Fill;
        }

        /// <summary>
        /// 返回RepurchaseListControl实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <returns></returns>
        public static RepurchaseListControl GetRepurchaseListControl(MainForm mainform)
        {
            if (repurchaseListControl == null)
                repurchaseListControl = new RepurchaseListControl(mainform);
            repurchaseListControl.RefreshDataGridViewData();
            return repurchaseListControl;
        }

        #region 功能方法实现

        /// <summary>
        /// 控件设置权限
        /// </summary>
        private void ControlsSetRights()
        {
            Button[] buttons = { button_query, button_create };
            RightsforControls.RightsforButton(mainform.Admin.RolePurviewtable, buttons);
            ContextMenuStrip[] menuStrips = { contextMenuStrip_dgv };
            RightsforControls.RightsforContextMenuStrip(mainform.Admin.RolePurviewtable, menuStrips);
        }

        /// <summary>
        /// 查看退货单商品
        /// </summary>
        private void ViewRepurchaseGoods()
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                String repurchaseno = this.dataGridView1.SelectedRows[0].Cells["repurchase_no"].Value.ToString();
                RepurchaseGoodsListControl repurchaseGoodsListControl = RepurchaseGoodsListControl.GetRepurchaseGoodsListControl(mainform, repurchaseno);
                mainform.AddDataGridViewPanelControl(repurchaseGoodsListControl);
            }
        }

        /// <summary>
        /// 删除退货单
        /// </summary>
        private void DeleteRepurchase()
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
                {
                    sb.Append(row.Cells["repurchase_no"].Value.ToString()).Append(",");
                }
                sb.Remove(sb.Length - 1, 1);
                int count = this.repurchaseService.DeleteBillRepurchase(sb.ToString());
                if (count > 0)
                {
                    MessageBox.Show("删除成功！");
                    this.RefreshDataGridViewData();
                }
                else
                    MessageBox.Show("删除失败！");
            }
        }

        #endregion

        #region IDataGridViewData 成员

        void IDataGridViewData.EnterkeyEventHandler()
        {
            this.ViewRepurchaseGoods();
        }

        void IDataGridViewData.GenerateGridViewColumns(DataGridView dgv)
        {
            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.Columns.Clear();
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("id", null, true, 0, null, null, false, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("repurchase_no", "退货单号", true, 12, ActKey.LEFT, ActKey.LEFT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("numbers", "商品数量", true, 6, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("goods_total", "商品金额", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("repurchase_total", "退货金额", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("fare", "运费", true, 7, ActKey.CENTER, ActKey.CENTER, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("other_cost", "其它费用", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("count_total", "退款总额", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("return_cost", "退货成本", true, 7, ActKey.RIGHT, ActKey.RIGHT, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("admin_name", "退货人", true, 8, ActKey.CENTER, ActKey.CENTER, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("repurchase_date", "退货日期", true, 8, ActKey.CENTER, ActKey.CENTER, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("note", "备注", true, 10, ActKey.CENTER, ActKey.CENTER, true, false));
            this.dataGridView1.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("is_refund", "是否退款", true, 8, ActKey.CENTER, ActKey.CENTER, true, false));
        }

        void IDataGridViewData.GetBindingData(int rowindex, int pageindex, int pagesize)
        {
            try
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String repurchaseno = textbox_repurchaseno.Text.Trim();
                String adminUsername = mainform.UsernameForQuery;
                String startdate = String.Empty;
                String enddate = String.Empty;
                if (dateTimePicker_startdate.Checked && dateTimePicker_enddate.Checked &&
                    dateTimePicker_enddate.Value.CompareTo(dateTimePicker_startdate.Value) >= 0)
                {
                    startdate = dateTimePicker_startdate.Value.ToShortDateString();
                    enddate = dateTimePicker_enddate.Value.ToShortDateString();
                }

                DataTable dt = this.repurchaseService.GetBillRepurchaseTable(pageindex, pagesize, enterpriseNo, null, repurchaseno, null,
                    adminUsername, null, startdate, enddate, null, "id");
                this.dataGridView1.DataSource = dt;
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (rowindex > 0)
                        dataGridView1.Rows[0].Selected = false;
                    dataGridView1.Rows[rowindex].Selected = true;
                }
                dataGridView1.Columns[0].Visible = false;

                mainform.SetPageInfo(dataGridView1.Recordcount, pageindex, pagesize);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        long IDataGridViewData.GetBindingDataRecord()
        {
            long record = 0;
            try
            {
                String enterpriseNo = mainform.Admin.EnterpriseNo;
                String repurchaseno = textbox_repurchaseno.Text.Trim();
                String adminUsername = mainform.UsernameForQuery;
                String startdate = String.Empty;
                String enddate = String.Empty;
                if (dateTimePicker_startdate.Checked && dateTimePicker_enddate.Checked &&
                    dateTimePicker_enddate.Value.CompareTo(dateTimePicker_startdate.Value) >= 0)
                {
                    startdate = dateTimePicker_startdate.Value.ToShortDateString();
                    enddate = dateTimePicker_enddate.Value.ToShortDateString();
                }
                record = this.repurchaseService.GetBillRepurchaseRecord(enterpriseNo, null, repurchaseno, null, adminUsername,
                    null, startdate, enddate);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return record;
        }

        #endregion

        #region IReloadData 成员

        void IReloadData.ReloadDataGridViewData(object param)
        {
            this.RefreshDataGridViewData();
        }

        #endregion

        #region 刷新数据

        /// <summary>
        /// 刷新数据
        /// </summary>
        public void RefreshDataGridViewData()
        {
            this.dataGridView1.LoadingData();
        }

        #endregion

        #region 重写键盘事件

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            if (keyData == Keys.Up || keyData == Keys.Down)
            {
                this.dataGridView1.Focus();
            }
            else if (keyData == Keys.F8)
                this.RefreshDataGridViewData();
            else if (keyData == Keys.F9)
            {
                RepurchaseAddForm repurchaseAddForm = RepurchaseAddForm.GetRepurchaseAddForm(mainform, this);
                repurchaseAddForm.Show();
            }
            return b;
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_query_Click(object sender, EventArgs e)
        {
            this.RefreshDataGridViewData();
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_create_Click(object sender, EventArgs e)
        {
            RepurchaseAddForm repurchaseAddForm = RepurchaseAddForm.GetRepurchaseAddForm(mainform, this);
            repurchaseAddForm.Show();
        }

        /// <summary>
        /// 查看进货商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_view_Click(object sender, EventArgs e)
        {
            this.ViewRepurchaseGoods();
        }

        /// <summary>
        /// 删除进货单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_delete_Click(object sender, EventArgs e)
        {
            this.DeleteRepurchase();
        }

        /// <summary>
        /// 单元格双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            this.ViewRepurchaseGoods();
        }

        #endregion

        #region IPrinter 成员

        DataGridView IPrinter.GetAllRows()
        {
            try
            {
                ((IDataGridViewData)this).GetBindingData(0, 0, 0);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return this.dataGridView1;
        }

        DataGridView IPrinter.GetSelectedRows()
        {
            return this.dataGridView1;
        }

        void IPrinter.VisibleColumn(string columnname)
        {
            try
            {
                if (this.dataGridView1.Columns[columnname].Visible)
                    this.dataGridView1.Columns[columnname].Visible = false;
                else
                    this.dataGridView1.Columns[columnname].Visible = true;
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        #endregion
    }
}
